//
//  RemoteViewController.m
//  OST
//
//  Created by mac on 13-7-11.
//  Copyright (c) 2013年 mac. All rights reserved.
//

#import "RemoteViewController.h"
#import "SetData.h"
#import "DeviceListCell.h"
#import "PersistableInfo.h"
#import "RemoteAVViewController.h"
#import "RemoteAirViewController.h"
#import "Utitlity.h"
#import "ChangeInfoDialog.h"
#import "BottomView.h"
#import "MMProgressHUD.h"


@interface RemoteViewController ()<DeviceListCellDelegate,changeDataDicDelegate>{
    NSString *ipUrl;
    PersistableInfo*info;
    
    BOOL isLoading;
    
    NSMutableArray *resultItem;
}

@end

@implementation RemoteViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    closeNextPage = YES;
    threadLoadData = NO;
    
    BottomView *bottomView = [self addBottomView];
    bottomView.btn_camera.hidden = YES;
    dataTableView.frame = CGRectMake(0, 0, 320, self.view.frame.size.height - 60);
    self.title =@"Remote";
    
    //icons = [NSArray arrayWithObjects:@"sur_0",@"sur_1",@"sur_2", nil];
    
    
    [self refreshData];
    [self requestGetRoomList];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:YES];
    isLoading = YES;
}

-(CGFloat)rowHeight
{
    return 76;
}

- (UITableViewCell *)cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
	NSUInteger row=[indexPath row];
    static NSString *DeviceListCellIdentifier = @"DeviceListCellIdentifier";
    DeviceListCell *cell = (DeviceListCell*)[dataTableView dequeueReusableCellWithIdentifier:DeviceListCellIdentifier];
    if (cell==nil) {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"DeviceListCell" owner:self options:nil]lastObject];
        [cell initView];
        cell.btn_refresh.hidden = YES;
        cell.remoteChnageBtn.hidden = NO;
        cell.changeBtn.hidden = YES;
        cell.delegate = self;
//        cell.icon.image = [UIImage imageNamed:[icons objectAtIndex:row%[icons count]]];
    }
    NSDictionary *rowData = [self.rows objectAtIndex:row];
    NSMutableDictionary *muDic = [rowData mutableCopy];
    NSString *strUuid = [[GlobalService sharedInstance].curOperationDeviceUUID stringByReplacingOccurrencesOfString:@":" withString:@""];
    NSString *zidStr = muDic[@"ZID"];
    NSString *appStr = [NSString stringWithFormat:@"%@%@",strUuid,zidStr];
    [muDic setObject:appStr forKey:@"uuid"];
     NSString *rowStr = [NSString stringWithFormat:@"%d",row];
    [muDic setObject:rowStr forKey:@"indexPath"];
    [cell setRemoteCellData:muDic];
//    cell.labelName.text = [rowData objectForKey:@"Alias"];
    return cell;
}

-(void)didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSUInteger row=[indexPath row];
    NSDictionary *rowData = [self.rows objectAtIndex:row];
    NSMutableDictionary *muDic = [rowData mutableCopy];
    NSString *strUuid = [[GlobalService sharedInstance].curOperationDeviceUUID stringByReplacingOccurrencesOfString:@":" withString:@""];
    NSString *zidStr = muDic[@"ZID"];
    NSString *appStr = [NSString stringWithFormat:@"%@r%@",strUuid,zidStr];
    [muDic setObject:appStr forKey:@"uuid"];
    NSString *rowStr = [NSString stringWithFormat:@"%d",row];
    [muDic setObject:rowStr forKey:@"indexPath"];
    NSInteger kind = [[muDic objectForKey:@"DeviceType"] integerValue];
    if (kind == 6) {
        RemoteAirViewController *air = [[RemoteAirViewController alloc]init];
        air.Rdata = rowData;
        PersistableInfo *infoaaa = [DeviceListCell getRemoteInfo:muDic];
        air.title = infoaaa.name;
//        air.title = [rowData objectForKey:@"Alias"];
        [self.navigationController pushViewController:air animated:YES];
    }else{
        RemoteAVViewController *air = [[RemoteAVViewController alloc]init];
        air.data = rowData;
        air.title = [rowData objectForKey:@"Alias"];
        [self.navigationController pushViewController:air animated:YES];
    }
    
}

-(NSArray *)loadPageData:(int)page
{
    [activity startAnimating];
    
    ipUrl = [Utitlity judgeipUrl];
    isLoading = NO;
    
    if (ipUrl)
    {
        NSString *loadStr = [NSString stringWithFormat:@"http://%@/cgi-bin/Get.cgi?Get=1",ipUrl];
        [Utitlity commonHTTPMethod:loadStr responseType:jsonType success:^(AFHTTPRequestOperation *operation, id responseObject) {
            [activity stopAnimating];
            
            if (!responseObject || ![responseObject isKindOfClass:[NSDictionary class]]) return;
            
            isLoading = YES;
            resultItem = [[NSMutableArray alloc] init];
//            NSMutableArray *result = [NSMutableArray array];
            {
                NSArray *devList = responseObject[@"data"];
                for (NSDictionary *item in devList) {
                    
                    NSInteger deviceType = [[item objectForKey:@"DeviceType"] integerValue];
                    if ( deviceType == 6) {
                        
                        [resultItem addObject:item];
                    }
                }
            }
            NSLog(@"resultItem:%@",responseObject);
            [super doneLoadingTableViewData:resultItem];
            
        }failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"error:%@",error);
        }];
    }
    else
    {
        [[CMDDataProcessor sharedInstance] getDeviceListResultDataWithDataRecivedBlock:^(id data) {
            
            if (!data || ![data isKindOfClass:[NSDictionary class]]) return;
            
            if ([data[@"state"] isKindOfClass:[NSNumber class]])
            {
                return;
            }
            
            if ([data[@"state"] isEqualToString:@"Success"])
            {
                [activity stopAnimating];
                isLoading = YES;
                NSMutableArray *result = [NSMutableArray array];
                {
                    if([data[@"data"] isKindOfClass:[NSArray class]])
                    {
                        NSArray *devList = data[@"data"];
                        for (NSDictionary *item in devList)
                        {
                            NSInteger deviceType = [[item objectForKey:@"DeviceType"] integerValue];
                            if ( deviceType == 6) {
                                
                                [result addObject:item];
                            }
                        }
                    }
                }
                
                [super doneLoadingTableViewData:result];
            }
        }];
    }
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        if (!isLoading)
        {
            [self loadPageData:1];
        }
    });
    
    return nil;
}

//remote delegate
- (void)changeRemoteInfo:(NSDictionary *)data cell:(DeviceListCell *)cell
{
    ChangeInfoDialog  *yijianview = [[[NSBundle mainBundle] loadNibNamed:@"ChangeInfoDialog" owner:self options:nil]lastObject];
    [yijianview initView];
    yijianview.delegate = self;
    [yijianview setRoomDataList:_roomDataList];
    [yijianview setRemoteData:data cell:cell];
    [yijianview pageStart];
}

- (void)changeRemoteDic:(NSDictionary *)dic
{
    ipUrl = [Utitlity judgeipUrl];
    if (ipUrl)
    {
        int i;
        for (i = 0; i < [resultItem count];i++)
        {
            NSDictionary *proDic = [resultItem objectAtIndex:i];
            if([dic[@"ZID"] isEqualToString:proDic[@"ZID"]])
            {
                NSMutableDictionary *reDic = [dic mutableCopy];
                [resultItem replaceObjectAtIndex:i withObject:reDic];
            }
        }
        [MMProgressHUD showWithStatus:@"修改名字中...."];
        [MMProgressHUD dismissWithSuccess:@"修改名字成功"];
        
        [super doneLoadingTableViewData:resultItem];
    }
    else
    {
        [MMProgressHUD showWithTitle:@"修改名称错误" status:@"只能在局域网内进行修改"];
        [MMProgressHUD dismissAfterDelay:1];
    }
}

- (void)changeInfoDialogWithData:(NSDictionary *)dic changeToRoom:(RoomItemModel *)changeRoomData {
    
    for (NSInteger i=0; i<self.rows.count; i++) {
        NSDictionary *data = self.rows[i];
        if ([data[@"ZID"] isEqualToString:dic[@"ZID"]]) {
            
            NSNumber *rooId = dic[@"Room"];
            NSMutableDictionary *reDic = [data mutableCopy];
            reDic[@"Room"] = rooId;
            [self.rows replaceObjectAtIndex:i withObject:reDic];
            [dataTableView reloadData];
            break;
        }
    }
}


@end
